/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import dao.LoaiSanPhamDAO;
import dao.SanPhamDAO;
import java.awt.Component;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import pojo.LoaiSanPham;
import pojo.SanPham;

/**
 *
 * @author softviet
 */
public class SanPhamGUI extends javax.swing.JDialog {

    /**
     * Creates new form SanPhamGUI
     */
    private SanPham sanPham;
    private JErrorProvider errorProvider;
    private MyEventListener ButtonLuuClickedListener;
    private static Logger logger = Logger.getLogger(SanPhamGUI.class);
    private SanPham oldSanPham;

    public SanPhamGUI(java.awt.Frame parent, boolean modal, SanPham sanPham) throws Exception {
        super(parent, modal);
        initComponents();
        errorProvider = new JErrorProvider();
        this.sanPham = sanPham;
        oldSanPham = new SanPham();
        oldSanPham.setDonGia(sanPham.getDonGia());
        oldSanPham.setIsDelete(false);
        oldSanPham.setLoaiSanPham(sanPham.getLoaiSanPham());
        oldSanPham.setTenSanPham(sanPham.getTenSanPham());
        SetTabOder();
        FormatControl();
        AutoLoad();
        if (sanPham.getId() == 0) {
            this.setTitle("Thêm sản phẩm");
        } else {
            this.setTitle("Sửa sản phẩm");
            SetDataToControl();
        }
    }

    private void SetTabOder() {
        IndexedFocusTraversalPolicy indexedFocusTraversalPolicy = new IndexedFocusTraversalPolicy();
        indexedFocusTraversalPolicy.addIndexedComponents(new Component[]{txtTenSanPham, cboLoaiSanPham, txtDonGia, btnLuu, btnThoat});
        setFocusTraversalPolicy(indexedFocusTraversalPolicy);
    }

    private void FormatControl() {
        Utility.FormatDecimalTextfield(txtDonGia);
    }

    private void AutoLoad() throws Exception {
        List<LoaiSanPham> loaiSanPhams = (List<LoaiSanPham>) LoaiSanPhamDAO.LayDanhSach(LoaiSanPham.class, MainGUI.nguoiDung);
        Collections.sort(loaiSanPhams, new Comparator<LoaiSanPham>() {
            @Override
            public int compare(LoaiSanPham o1, LoaiSanPham o2) {
                return o1.getTenLoaiSanPham().compareTo(o2.getTenLoaiSanPham());
            }
        });
        Utility.SetDataSourceInCombo(loaiSanPhams, cboLoaiSanPham);
        cboLoaiSanPham.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof LoaiSanPham) {
                    LoaiSanPham loaiSanPham = (LoaiSanPham) value;
                    setText(loaiSanPham.getTenLoaiSanPham());
                }
                return this;
            }
        });
        cboLoaiSanPham.setSelectedIndex(-1);
    }

    private int CheckDataBeforeLuu() {
        int dem = 0;
        errorProvider.clear();
        if (txtTenSanPham.getText().trim().isEmpty()) {
            errorProvider.setError(txtTenSanPham, "required");
            dem++;
        }
        if (cboLoaiSanPham.getModel().getSelectedItem() == null) {
            errorProvider.setError(cboLoaiSanPham, "required");
            dem++;
        }
        if (txtDonGia.getText().isEmpty()) {
            errorProvider.setError(txtDonGia, "required");
            dem++;
        }
        return dem;
    }

    private void SetDataToControl() {
        txtTenSanPham.setText(sanPham.getTenSanPham());
        cboLoaiSanPham.getModel().setSelectedItem(sanPham.getLoaiSanPham());
        txtDonGia.setValue(sanPham.getDonGia());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtTenSanPham = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cboLoaiSanPham = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        txtDonGia = new javax.swing.JFormattedTextField();
        btnLuu = new javax.swing.JButton();
        btnThoat = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("Tên sản phẩm");

        jLabel2.setText("Loại sản phẩm");

        jLabel3.setText("Đơn giá");

        txtDonGia.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtDonGiaFocusLost(evt);
            }
        });

        btnLuu.setText("Lưu");
        btnLuu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLuuActionPerformed(evt);
            }
        });

        btnThoat.setText("Thoát");
        btnThoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnThoatActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtTenSanPham)
                    .addComponent(cboLoaiSanPham, 0, 191, Short.MAX_VALUE)
                    .addComponent(txtDonGia))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(106, Short.MAX_VALUE)
                .addComponent(btnLuu)
                .addGap(18, 18, 18)
                .addComponent(btnThoat)
                .addGap(101, 101, 101))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtTenSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cboLoaiSanPham, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtDonGia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnLuu)
                    .addComponent(btnThoat))
                .addContainerGap(19, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnThoatActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_btnThoatActionPerformed

    private void txtDonGiaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtDonGiaFocusLost
        // TODO add your handling code here:
        if (txtDonGia.getText().isEmpty()) {
            txtDonGia.setValue(null);
        }
    }//GEN-LAST:event_txtDonGiaFocusLost

    private void btnLuuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLuuActionPerformed
        // TODO add your handling code here:
        if (CheckDataBeforeLuu() > 0) {
            return;
        }
        sanPham.setDonGia(Double.parseDouble(txtDonGia.getValue().toString()));
        sanPham.setIsDelete(false);
        sanPham.setLoaiSanPham((LoaiSanPham) cboLoaiSanPham.getModel().getSelectedItem());
        sanPham.setTenSanPham(txtTenSanPham.getText().trim());
        if (sanPham.getId() == 0) {
            try {
                if (ButtonLuuClickedListener == null) {
                    return;
                }
                int id = SanPhamDAO.Them(sanPham);
                sanPham.setId(id);
                JOptionPane.showMessageDialog(null, "Thêm thành công");
                ButtonLuuClickedListener.myEventOccured(sanPham);
                dispose();
            } catch (Exception ex) {
                logger.error(new Date().toString(), ex);
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        } else {
            try {
                SanPhamDAO.Sua(sanPham);
                JOptionPane.showMessageDialog(this, "Cập nhật thành công");
                dispose();
            } catch (Exception ex) {
                sanPham.setDonGia(oldSanPham.getDonGia());
                sanPham.setIsDelete(false);
                sanPham.setLoaiSanPham(oldSanPham.getLoaiSanPham());
                sanPham.setTenSanPham(oldSanPham.getTenSanPham());
                logger.error(new Date().toString(), ex);
                JOptionPane.showMessageDialog(this, ex.getMessage());
            }
        }
    }//GEN-LAST:event_btnLuuActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLuu;
    private javax.swing.JButton btnThoat;
    private javax.swing.JComboBox cboLoaiSanPham;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JFormattedTextField txtDonGia;
    private javax.swing.JTextField txtTenSanPham;
    // End of variables declaration//GEN-END:variables

    /**
     * @param ButtonLuuClickedListener the ButtonLuuClickedListener to set
     */
    public void setButtonLuuClickedListener(MyEventListener ButtonLuuClickedListener) {
        this.ButtonLuuClickedListener = ButtonLuuClickedListener;
    }
}
